let arr = [
    { id: 2, name: "雍正", parentId: 1 },
    { id: 3, name: "乾隆", parentId: 2 },
    { id: 4, name: "嘉庆", parentId: 3 },
]
export default function buildMenu(arr: any) {

    //1. 先从数组中找出顶级菜单
    let ids = arr.map((item: any) => item.id)

    let treeMenu: any = []

    //遍历arr，判断谁的parentId不在ids数组中，谁就是顶级菜单
    arr.forEach((item: any) => {
        if (!ids.includes(item.pid)) {
        // if (ids===item.departmentId) {
            // 说明item就是顶级菜单
            // 再去找item的children
            findChildren(arr, item)
            treeMenu.push(item)
        }
    });
    return treeMenu
}

function findChildren(arr: any, menu: any) {
    menu.children = []
    arr.forEach((item:any) => {
        if (item.pid === menu.id) {
            menu.children.push(item)
            findChildren(arr, item)
        }
    })
}